package com.xhg.util.image;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.xhg.common.Constants;
import com.xhg.util.propUtil.Prop;
import com.xhg.util.propUtil.PropertiesUtil;

/**
 * @createTime 2014-12-17
 * @author wjw
 */
public class Captcha {
	
	private static DefaultKaptcha captchaProducer=new DefaultKaptcha();
	
	/**
	 * 初始化验证码生成参数
	 */
	static{
		Prop prop=PropertiesUtil.loadProperty("config/param.properties",Constants.DEFAULT_ENCODING);
		Config config=new Config(prop.getProperties());//获取图像参数
		captchaProducer.setConfig(config);
	}
	/**
	 * 生成验证码
	 */
	public static void  getCaptcha(HttpServletResponse response,HttpSession session){
		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control","no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		response.setContentType("image/jpeg");
		String capText = captchaProducer.createText();
		session.setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, capText);
		BufferedImage bi = captchaProducer.createImage(capText);
		ServletOutputStream out=null;
			try {
				out= response.getOutputStream();
				ImageIO.write(bi, "jpg", out);
				out.flush();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
}
